using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using System.Linq;
using System.Collections.Generic;

namespace SPAdminMenu.Features.SPAdminMenu_Feature_Activate
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    

    [Guid("2466c2ac-ac42-4f61-82aa-0d8b40d9c476")]
    public class SPAdminMenu_Feature_ActivateEventReceiver : SPFeatureReceiver
    {

        private string[] folderUrls = { "Style Library/SPAdminMenu/Files" };
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //SPSite site = properties.Feature.Parent as SPSite;
            //if (site != null)
            //{
            //    SPWeb rootWeb = site.RootWeb;

            //    SPList styleLibrary = rootWeb.Lists.TryGetList("Style Library");
            //    if (styleLibrary != null)
            //    {
            //        SPListItemCollection folders = styleLibrary.Folders;
            //        string featureId = properties.Feature.Definition.Id.ToString();

            //        foreach (string folderUrl in folderUrls)
            //        {
            //            SPFolder folder = GetFolderByUrl(folders, folderUrl);
            //            if (folder != null)
            //            {
            //                PublishFiles(folder, featureId);
            //            }
            //        }
            //    }
            //}
        }


        private static SPFolder GetFolderByUrl(SPListItemCollection folders, string folderUrl)
        {
            if (folders == null)
            {
                throw new ArgumentNullException("folders");
            }

            if (String.IsNullOrEmpty(folderUrl))
            {
                throw new ArgumentNullException("folderUrl");
            }

            SPFolder folder = null;

            SPListItem item = (from SPListItem i
                               in folders
                               where i.Url.Equals(folderUrl, StringComparison.InvariantCultureIgnoreCase)
                               select i).FirstOrDefault();

            if (item != null)
            {
                folder = item.Folder;
            }

            return folder;
        }


        private static void PublishFiles(SPFolder folder, string featureId)
        {
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }

            if (String.IsNullOrEmpty(featureId))
            {
                throw new ArgumentNullException("featureId");
            }

            SPFileCollection files = folder.Files;
            var checkedOutFiles = from SPFile f
                                  in files
                                  where String.Equals(f.Properties["FeatureId"] as string, featureId, StringComparison.InvariantCultureIgnoreCase) &&
                                  f.Level == SPFileLevel.Checkout
                                  select f;

            foreach (SPFile f in checkedOutFiles)
            {
                f.CheckIn(String.Empty, SPCheckinType.MajorCheckIn);
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite spSite = properties.Feature.Parent as SPSite;
            if (spSite != null)
            {
                SPWeb spWeb = spSite.RootWeb;

                if (spWeb != null)
                {
                    List<string> lListInstances = new List<string>();
                    List<string> lStyleLibrarySubDirs = new List<string>();
                    List<string> lWebParts = new List<string>();


                    //add all style library sub directories.
                    lStyleLibrarySubDirs.Add("SPAdminMenu");


                    //Delete style library files
                    try
                    {
                        if (lStyleLibrarySubDirs.Count > 0)
                        {
                            //go through each list
                            for (int i = 0; i < spWeb.Lists.Count; i++)
                            {
                                if (spWeb.Lists[i].RootFolder.Name.Equals("Style Library"))
                                {
                                    SPDocumentLibrary styleLib = (SPDocumentLibrary)spWeb.Lists[i];
                                    foreach (String sSubDir in lStyleLibrarySubDirs)
                                    {
                                        foreach (SPListItem subFolder in styleLib.Folders)
                                        {
                                            //if themable dir
                                            if (subFolder.Name.Equals(sSubDir))
                                            {
                                                if (subFolder.Folder.ParentFolder.Name.Equals("Style Library"))
                                                {
                                                    subFolder.Delete();
                                                    subFolder.Update();
                                                    styleLib.Update();
                                                }
                                            } //end if feature folder dir
                                        } //end going through each top level folder
                                    } //end going through each primary sub folder added by feature
                                } //end if this is the style library
                            } //end going through each top level site list (looking for style library)
                        }
                    }
                    catch { }

                }
                spSite.Close();
            }
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
